package com.xing.lei.happy.utils;


import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ExcelTools {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelTools.class);

    public static void export(HttpServletResponse response, String sheetName, String[] titles, Map<String, Integer> pos, List<Map<String, Object>> data) {
        try (Workbook wb = new XSSFWorkbook(); OutputStream os = response.getOutputStream()) {
            CellStyle css = getTextStyle(wb);
            String s = StringUtils.isBlank(sheetName) ? "分表1" : sheetName;
            Sheet sheet = wb.createSheet(s);
            int ds = 0;
            if (ArrayUtils.isNotEmpty(titles)) {
                setTitle(sheet, titles, css);
                ds = 1;
            }
            if (MapUtils.isEmpty(pos) || CollectionUtils.isEmpty(data)) {
                return;
            }
            setDate(sheet, css, ds, pos, data);
            wb.write(os);
        } catch (Exception e) {
            LOGGER.error("导出Excel错误", e);
        }
    }

    public static void write(String filePath, String sheetName, String[] titles, Map<String, Integer> pos, List<Map<String, Object>> data) {
        try (Workbook wb = new HSSFWorkbook(); OutputStream os = new FileOutputStream(filePath)) {
            CellStyle css = getTextStyle(wb);
            String s = StringUtils.isBlank(sheetName) ? "分表1" : sheetName;
            Sheet sheet = wb.createSheet(s);
            int ds = 0;
            if (ArrayUtils.isNotEmpty(titles)) {
                setTitle(sheet, titles, css);
                ds = 1;
            }
            if (MapUtils.isEmpty(pos) || CollectionUtils.isEmpty(data)) {
                return;
            }
            setDate(sheet, css, ds, pos, data);
            wb.write(os);
        } catch (Exception e) {
            LOGGER.error("导出Excel错误", e);
        }
    }

    private static void setDate(Sheet sheet, CellStyle css, int ds, Map<String, Integer> pos, List<Map<String, Object>> data) {
        if (MapUtils.isEmpty(pos) || CollectionUtils.isEmpty(data)) {
            return;
        }
        int l = data.size();
        for (int i = 0; i < l; i++) {
            setCell(sheet.createRow(i + ds), css, pos, data.get(i));
        }
    }

    private static void setCell(Row row, CellStyle css, Map<String, Integer> pos, Map<String, Object> data) {
        if (MapUtils.isEmpty(pos) || MapUtils.isEmpty(data)) {
            return;
        }
        for (Map.Entry<String, Object> d : data.entrySet()) {
            Cell cell = row.createCell(pos.computeIfAbsent(d.getKey(), k -> pos.size() + 1));
            cell.setCellStyle(css);
            cell.setCellValue(String.valueOf(d.getValue()));
        }
    }

    private static CellStyle getTextStyle(Workbook wb) {
        CellStyle css = wb.createCellStyle();
        DataFormat format = wb.createDataFormat();
        css.setDataFormat(format.getFormat("@"));
        return css;
    }

    private static void setTitle(Sheet sheet, String[] titles, CellStyle css) {
        if (Objects.isNull(sheet) || ArrayUtils.isEmpty(titles)) {
            return;
        }
        Row row = sheet.createRow(0);
        int l = titles.length;
        for (int i = 0; i < l; i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(css);
            cell.setCellValue(titles[i]);
        }
    }

    private ExcelTools() {
        throw new IllegalStateException("Utility class");
    }
}
